package com.free.rabbitmq.listener;

import com.free.rabbitmq.common.constant.RabbitConstant;
import com.free.rabbitmq.common.model.MsgMail;
import com.free.rabbitmq.common.util.MessageHelper;
import com.free.rabbitmq.proxy.BaseConsumer;
import com.free.rabbitmq.proxy.BaseConsumerProxy;
import com.free.rabbitmq.common.config.RabbitConfig;
import com.free.rabbitmq.common.service.MsgLogService;
import com.free.rabbitmq.consumer.MailConsumer;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class RabbitTopicListener {

    @Autowired
    private MsgLogService msgLogService;

    @Autowired
    private MailConsumer mailConsumer;

    @RabbitListener(queues = RabbitConstant.ExchangeQueues.MAIL_QUEUE_NAME)
    public void consume(Message message, Channel channel) throws IOException {
        MsgMail mail = MessageHelper.msgToObj(message, MsgMail.class);
        log.info("RabbitTopicListener.consume收到消息: {}", mail.toString());
        //休眠1s后在处理，目的是防止和生产者消息投递的confirm回调发生并发修改status冲突，导致status状态修改不正确
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(mailConsumer, msgLogService);
        BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
        if (null != proxy) {
            proxy.consume(message, channel);
        }
    }

}
